<template>
   <div class="app-container">
      <!-- 顶部工具栏：左侧+按钮与标签，右侧搜索与下载 -->
      <!-- 第一行：搜索与下载（右上角）占满行宽 -->
      <el-row :gutter="10" class="mb8">
         <el-col :span="24" style="text-align: right;">
            <el-input
               v-model="queryParams.s"
               placeholder="请输入"
               clearable
               style="width: 220px; margin-right: 10px;"
               @keyup.enter="handleQuery"
            />
            <el-button type="primary" icon="Search" @click="handleQuery" style="margin-right: 10px;">搜索</el-button>
            <el-button type="primary" icon="Download" @click="handleExport" v-hasPermi="['store:export']">下载</el-button>
         </el-col>
      </el-row>

      <!-- 第二行：标签区域（整行宽度） -->
      <el-row :gutter="10" class="mb4 align-center">
         <el-col :span="24">
            <div class="toolbar-left">
               <!-- 动态标签页：固定“全部”，其余可增删改（右侧自带+号） -->
               <el-tabs
                  v-model="activeTabName"
                  type="card"
                  addable
                  @tab-add="onAddTab"
                  @tab-remove="onRemoveTab"
                  @tab-click="onTabClick"
                  class="store-tabs"
               >
                  <!-- 全部 -->
                  <el-tab-pane label="全部" name="all" :closable="false">
                    <!-- 表格模块（全部） -->
                    <div class="tab-panel">
                      <el-table v-loading="loading" :data="storeList" stripe>
                         <el-table-column type="index" label="序号" width="60" align="center" />
                         <el-table-column label="品牌" align="center" prop="brand_name" :show-overflow-tooltip="true">
                            <template #default="scope">
                               <span>{{ scope.row.brand_name || '' }}</span>
                            </template>
                         </el-table-column>
                         <el-table-column label="编号" align="center" prop="bh" :show-overflow-tooltip="true">
                            <template #default="scope">
                               <span style="color: #ff7a00;">{{ scope.row.bh || '' }}</span>
                            </template>
                         </el-table-column>
                         <el-table-column label="名称" align="center" prop="mc" :show-overflow-tooltip="true" />
                         <el-table-column label="区域" align="center" prop="qymc" :show-overflow-tooltip="true">
                            <template #default="scope">
                               <span>{{ scope.row.qymc || '' }}</span>
                            </template>
                         </el-table-column>
                         <el-table-column label="排序" align="center" prop="px" :show-overflow-tooltip="true" />
                         <el-table-column label="状态" align="center" prop="zt">
                            <template #default="scope">
                               <el-tag :type="scope.row.zt === '1' ? 'success' : 'danger'">
                                  {{ scope.row.zt === '1' ? '有效' : '无效' }}
                               </el-tag>
                            </template>
                         </el-table-column>
                         <el-table-column label="备注" align="center" prop="bz" :show-overflow-tooltip="true">
                            <template #default="scope">
                               <span>{{ scope.row.bz || '' }}</span>
                            </template>
                         </el-table-column>
                      </el-table>
                      <pagination
                         v-show="total > 0"
                         :total="total"
                         v-model:page="queryParams.pageNum"
                         v-model:limit="queryParams.pageSize"
                         @pagination="getList"
                      />
                    </div>
                  </el-tab-pane>
                  <el-tab-pane
                     v-for="item in dynamicTabs"
                     :key="item.name"
                     :name="item.name"
                     :closable="true"
                  >
                    <template #label>
                      <div class="tab-label">
                        <span v-if="editTab !== item.name" @dblclick.stop="startEdit(item)">{{ item.label }}</span>
                        <el-input
                          v-else
                          v-model="editInput"
                          size="small"
                          @blur="confirmEdit(item)"
                          @keyup.enter="confirmEdit(item)"
                          @keyup.esc="cancelEdit"
                          style="width: 120px"
                        />
                      </div>
                    </template>
                    <!-- 表格模块（按标签过滤区域） -->
                    <div class="tab-panel">
                      <el-table v-loading="loading" :data="storeList" stripe>
                         <el-table-column type="index" label="序号" width="60" align="center" />
                         <el-table-column label="品牌" align="center" prop="brand_name" :show-overflow-tooltip="true">
                            <template #default="scope">
                               <span>{{ scope.row.brand_name || '' }}</span>
                            </template>
                         </el-table-column>
                         <el-table-column label="编号" align="center" prop="bh" :show-overflow-tooltip="true">
                            <template #default="scope">
                               <span style="color: #ff7a00;">{{ scope.row.bh || '' }}</span>
                            </template>
                         </el-table-column>
                         <el-table-column label="名称" align="center" prop="mc" :show-overflow-tooltip="true" />
                         <el-table-column label="区域" align="center" prop="qymc" :show-overflow-tooltip="true">
                            <template #default="scope">
                               <span>{{ scope.row.qymc || '' }}</span>
                            </template>
                         </el-table-column>
                         <el-table-column label="排序" align="center" prop="px" :show-overflow-tooltip="true" />
                         <el-table-column label="状态" align="center" prop="zt">
                            <template #default="scope">
                               <el-tag :type="scope.row.zt === '1' ? 'success' : 'danger'">
                                  {{ scope.row.zt === '1' ? '有效' : '无效' }}
                               </el-tag>
                            </template>
                         </el-table-column>
                         <el-table-column label="备注" align="center" prop="bz" :show-overflow-tooltip="true">
                            <template #default="scope">
                               <span>{{ scope.row.bz || '' }}</span>
                            </template>
                         </el-table-column>
                      </el-table>
                      <pagination
                         v-show="total > 0"
                         :total="total"
                         v-model:page="queryParams.pageNum"
                         v-model:limit="queryParams.pageSize"
                         @pagination="getList"
                      />
                    </div>
                  </el-tab-pane>
               </el-tabs>
            </div>
         </el-col>
      </el-row>

      <!-- 右侧抽屉：新增门店 -->
      <el-drawer v-model="drawer.open" title="新增" direction="rtl" size="420px" :with-header="true">
        <el-form ref="drawerRef" :model="drawer.form" :rules="drawer.rules" label-width="80px">
          <el-form-item label="编号" prop="bh">
            <el-input v-model="drawer.form.bh" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="名称" prop="mc">
            <el-input v-model="drawer.form.mc" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="备注" prop="bz">
            <el-input v-model="drawer.form.bz" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="排序" prop="px">
            <el-input-number v-model="drawer.form.px" :min="0" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="状态" prop="zt">
            <el-switch v-model="drawer.form.zt" active-value="1" inactive-value="0" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div style="text-align: right; width: 100%;">
            <el-button type="primary" @click="submitDrawer">保 存</el-button>
          </div>
        </template>
      </el-drawer>

      

      <!-- 添加或修改门店对话框 -->
      <el-dialog :title="title" v-model="open" width="600px" append-to-body>
         <el-form ref="storeRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="编号" prop="bh">
               <el-input v-model="form.bh" placeholder="请输入编号" />
            </el-form-item>
            <el-form-item label="名称" prop="mc">
               <el-input v-model="form.mc" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="区域" prop="qymc">
               <el-input v-model="form.qymc" placeholder="请输入区域" />
            </el-form-item>
            <el-form-item label="排序" prop="px">
               <el-input-number v-model="form.px" controls-position="right" :min="0" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="状态" prop="zt">
               <el-radio-group v-model="form.zt">
                  <el-radio label="1">有效</el-radio>
                  <el-radio label="0">无效</el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="bz">
               <el-input v-model="form.bz" type="textarea" placeholder="请输入备注" />
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Store">
import { listStore } from "@/api/store/store";
import { listRegion } from "@/api/data/region";

const { proxy } = getCurrentInstance();

const storeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const total = ref(0);
const title = ref("");
// 动态标签：固定“全部”，其余可增删改
const activeTabName = ref('all');
const dynamicTabs = ref([]);
const editTab = ref('');
const editInput = ref('');

// 抽屉：新增门店
const drawer = reactive({
  open: false,
  form: {
    bh: undefined,
    mc: undefined,
    bz: undefined,
    px: 1000,
    zt: '1'
  },
  rules: {
    bh: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
    mc: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
  }
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    s: undefined,
    zbh: undefined,
    brand: undefined,
    bh: undefined,
    mc: undefined,
    qymc: undefined
  },
  rules: {
    mc: [{ required: true, message: "门店名称不能为空", trigger: "blur" }],
    bh: [{ required: true, message: "门店编号不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询门店列表 */
function getList() {
  loading.value = true;
  
  // 根据选中的标签设置搜索参数
  const queryData = { ...queryParams.value };
  if (activeTabName.value === 'all') {
    queryData.qymc = undefined;
  } else {
    const current = dynamicTabs.value.find(t => t.name === activeTabName.value);
    queryData.qymc = current ? current.label : undefined;
  }
  
  listStore(queryData).then(response => {
    storeList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  });
}

/** 标签切换 */
function onTabClick() {
  queryParams.value.pageNum = 1;
  getList();
}

// 点击标签+ 触发：打开抽屉新增门店
function onAddTab() {
  drawer.open = true;
}

// 删除标签
function onRemoveTab(name) {
  const idx = dynamicTabs.value.findIndex(t => t.name === name);
  if (idx !== -1) {
    dynamicTabs.value.splice(idx, 1);
    // 删除后回到“全部”
    activeTabName.value = 'all';
    onTabClick();
  }
}

// 重命名（双击标签文字进入编辑）
function startEdit(item) {
  editTab.value = item.name;
  editInput.value = item.label;
}
function confirmEdit(item) {
  if (editInput.value) item.label = editInput.value;
  editTab.value = '';
  onTabClick();
}
function cancelEdit() {
  editTab.value = '';
}

// 抽屉提交
function submitDrawer() {
  proxy.$refs['drawerRef'].validate(valid => {
    if (!valid) return;
    // TODO: 在此调用后端新增接口
    proxy.$modal.msgSuccess('保存成功');
    drawer.open = false;
    // 保存后刷新当前列表
    getList();
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    bh: undefined,
    mc: undefined,
    qymc: undefined,
    px: 1000,
    zt: "1",
    bz: undefined
  };
  proxy.resetForm("storeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  activeTabName.value = 'all';
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加门店";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["storeRef"].validate(valid => {
    if (valid) {
      // 这里可以调用新增或修改接口
      proxy.$modal.msgSuccess("操作成功");
      open.value = false;
      getList();
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("store/export", {
    ...queryParams.value
  }, `store_${new Date().getTime()}.xlsx`);
}

getList();

// 加载区域作为标签（除“全部”）
function loadRegions() {
  listRegion({ pageNum: 1, pageSize: 9999 }).then(res => {
    dynamicTabs.value = (res.rows || []).map((r) => ({ name: String(r.regionCode), label: r.regionName }));
    // 若存在上海等默认首个区域，可保持当前激活，否则默认all
  })
}

loadRegions();
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.mb4 {
  margin-bottom: 4px;
}

.align-center {
  align-items: center;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
}

.tab-panel {
  margin-top: 6px;
}

.store-tabs {
  width: 100%;
}

.tab-item {
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: color 0.3s;
}

.tab-item.active {
  color: #ff7a00;
  font-weight: 500;
}

.tab-item:hover {
  color: #ff7a00;
}
</style>

